package com.hunktimes.wholesale.extension

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hunktimes.wholesale.net.TokenInvalidException
import com.hunktimes.wholesale.util.L
import com.hunktimes.wholesale.util.ToastUtil
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.net.UnknownHostException

/**
 * Author: Delete
 * Date: 2020/7/22 17:48
 * Description:
 *
 */

fun ViewModel.launch(
    block: suspend CoroutineScope.() -> Unit,
    onError: (e: Throwable) -> Unit = {},
    onComplete: () -> Unit = {}
) {
    viewModelScope.launch(CoroutineExceptionHandler { coroutineContext, throwable ->
        L.d("CoroutineExceptionHandler e -> $throwable")
        if (throwable is UnknownHostException) {
            ToastUtil.showErrorToast("网络似乎有一些小问题,请检查一下哦...")
        } else if (throwable is TokenInvalidException) {
            //拦截 token 失效
            //EventBus.getDefault().post(TokenInvalid())
        }
        onError(throwable)
    }) {
        try {
            block.invoke(this)
        } finally {
            onComplete()
        }

    }
}